import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_page/cartoon_business/widget/acg_source_manager.dart';
import 'package:xvideos/hj_page/cartoon_business/widget/cartoon_subset_alert.dart';
import 'package:xvideos/tools_base/event_bus/events.dart';
import 'package:xvideos/tools_base/widget/scroll_positioned_list/src/scrollable_positioned_list.dart';

import '../../../hj_model/acg/comic_chapters_model.dart';
import '../../../hj_model/cartoon_media_info.dart';
import '../../../hj_utils/api_service/acg_service.dart';
import '../../hj_utils/history_record_util.dart';
import '../../tools_base/event_bus/event_bus_util.dart';
import 'cartoon_read_page.dart';

class CartoonDetailLogic extends GetxController with GetTickerProviderStateMixin {
  String? id;
  CartoonMediaInfo? mediaInfo;

  bool showHeader = true;
  double showOffset = 245;
  bool collectLoading = false;
  bool get isCartoonType => manager.mediaInfo?.mediaType == 'image'; //是否是动画

  late ScrollController scrollController = ScrollController()
    ..addListener(() {
      if (scrollController.offset <= showOffset) {
        if (!showHeader) {
          showHeader = true;
          update(['header']);
        }
      } else {
        if (showHeader) {
          showHeader = false;
          update(['header']);
        }
      }
    });
  final ItemScrollController itemSCtrl = ItemScrollController();
  late ACGSourceManager manager;
  late StreamSubscription subscription;

  CartoonDetailLogic({this.id}) : manager = ACGSourceManager(id ?? ''); //初始化，加载子集

  @override
  void onReady() {
    super.onReady();
    loadData();
    //拉取子集
    manager.fetchAllEpisodes();
    subscription = eventBus.on<ACGMenuChanged>((event) {
      print('changeEpisodesIndex ACGMenuChanged === ${event.index}');
      itemSCtrl.jumpTo(index: event.index ?? 0);
    });
  }

  @override
  void onClose() {
    subscription.cancel();
    eventBus.off(subscription);

    super.onClose();
  }

  //获取媒体详情
  Future loadData() async {
    mediaInfo = await ACGService.getMediaInfo(id ?? '');
    if (mediaInfo != null) {
      HistoryRecordUtil.insertHistoryModel<CartoonMediaInfo>(mediaInfo!, HistoryRecordType.comics);
      manager.mediaInfo = mediaInfo;
      showOffset = mediaInfo?.mediaType == 'text' ? 300 : 320;
      print('保存集数 获取=== currentEpisode = ${manager.index}, mediaInfo.id = ${mediaInfo?.id ?? ''}');
    } else {
      mediaInfo = CartoonMediaInfo();
    }
    update();
  }

  //切换集数
  changeEpisode(int episode, bool jump) async {
    manager.changeEpisodesIndex(episode, jump: jump);
    print('保存集数 获取=== currentEpisode = ${manager.index}, mediaInfo.id = ${mediaInfo?.id}');
    play(); //播放
  }

  play() async {
    //判断权限
    ComicChapterInfo? info = await manager.getEpisodeHasPermisson(manager.index);
    if (info == null) return;
    if (isCartoonType) {
      Get.to(() => CartoonReadPage(manger: manager..index = manager.index));
    } else {
      Get.to(() => CartoonReadPage(manger: manager..index = manager.index));
    }
  }

  //集数弹窗
  onMenuAction() async {
    int episode = await Get.bottomSheet(
      CartoonSubSetAlert(sourceManager: manager),
      barrierColor: Colors.black.withOpacity(.2),
    );
    if (episode > -1) {
      changeEpisode(episode, true);
    }
  }
}
